package com.example.smart.ui.activity.home

import android.media.MediaPlayer
import com.czt.mp3recorder.MP3Recorder
import com.example.lib.extend.gone
import com.example.lib.extend.setOnDoubleClickListener
import com.example.lib.extend.verticalManager
import com.example.lib.extend.visi
import com.example.lib.utils.ToastUtils
import com.example.lib.utils.permission.RequestPermission
import com.example.lib.utils.statusbar.StatusBarUtils
import com.example.smart.R
import com.example.smart.adapter.home.AiConversationAdapter
import com.example.smart.base.adapter.BaseRecyclerAdapter
import com.example.smart.base.ui.activity.BaseTitleBarActivity
import com.example.smart.data.AiConversationData
import com.example.smart.databinding.ActivityAiConversationBinding
import com.example.smart.dialog.InputDialog
import com.example.smart.dialog.RecodeDialog
import com.example.smart.utils.handler.HandUtils
import java.io.File

class AiConversationActivity : BaseTitleBarActivity<ActivityAiConversationBinding>() {
    private var mRecode: MP3Recorder? = null
    private var mRecodePath = ""
    private var mRecodeTime = 0L
    private val questionMap = HashMap<String, String>()
    private val mAdapter by lazy {
        AiConversationAdapter(this@AiConversationActivity)
    }

    private val mDialog by lazy {
        InputDialog(this@AiConversationActivity)
    }

    private val mRecodeDialog by lazy {
        RecodeDialog(this@AiConversationActivity)
    }

    private val mMedia = MediaPlayer().also {
        it.setOnPreparedListener { player -> player.start() }
    }

    override fun layoutID() = R.layout.activity_ai_conversation

    override fun initView() {
        StatusBarUtils.setStateAndNavigationBar(this@AiConversationActivity,
            statusBarColor = com.example.lib.R.color.black_ececf8)
        setAppBarColor(getColor(com.example.lib.R.color.black_ececf8))
        title = getString(R.string.vaccines_msg53)

        binding.Recycler.verticalManager()
        binding.Recycler.adapter = mAdapter

    }

    override fun initData() {
        questionMap["绵羊需要打哪些疫苗？什么时候打最好？"] =
            "核心疫苗包括：\n" + "口蹄疫疫苗：春秋季各1次（3月/9月）\n" + "羊痘疫苗：春季接种（配种前30天）\n" + "三联四防疫苗：产羔前40天母羊接种\n注意：高原地区需增加包虫病疫苗，接种后观察30分钟"
        questionMap["牛群出现口流白沫怎么办？"] =
            "紧急处理步骤：\n" + "① 立即隔离病牛至下风处\n" + "② 检查口腔是否有异物（警惕中毒）\n" + "③ 测量体温（正常38-39.5℃）\n" + "④ 拍摄舌苔照片上传AI诊断\n疑似口蹄疫时用0.1%高锰酸钾清洗患处"
        questionMap["怎么判断羊只是普通腹泻还是传染病？"] =
            "鉴别要点：\n" + "普通腹泻：仅个别发生，粪便含未消化饲料，精神食欲正常。\n" + "传染性腹泻：同群多只连续发病，水样便带血/黏膜，体温升高至40℃以上。"
        questionMap["马匹突然转圈行走是什么病？"] =
            "可能提示：\n" + "脑炎（伴随高热/意识障碍）\n" + "寄生虫感染（脑包虫高发区）\n" + "中毒（检查饲草是否霉变）\n" + "立即停止使役，用蒙语唤醒测试意识状态"
        questionMap["驱虫药喂了三天还能见虫怎么办？"] =
            "科学应对：\n" + "① 拍照虫体确认种类（绦虫/线虫/吸虫）\n" + "② 交叉使用不同机理药物（苯并咪唑类+阿维菌素）\n" + "③ 配合环境消毒（石灰水喷洒畜栏）\n" + "草原地区建议实行\"驱虫日历\"：4月、7月、10月定期预防"
        questionMap["青霉素用量怎么计算？能和传统草药同用吗？"] =
            "标准剂量：\n" + "牛：2万单位/kg（每日2次）\n" + "羊：3万单位/kg（每日1次）\n" + "避免与含鞣酸的草药（如地榆）同时使用，间隔至少2小时"
        questionMap["隔壁牧场发现布病，我们该怎么防护？"] =
            "三级防控：\n" + "① 生物安全：暂停转场，设立消毒隔离带\n" + "② 人员防护：接触牲畜佩戴N95口罩\n" + "③ 监测预警：每周采血送检，AI分析群体抗体水平\n" + "传统预防：每日饮用煮沸的沙棘叶茶"
        questionMap["如何用手机检查草场安全？"] =
            "智能防疫助手功能：\n" + "拍摄牧草→AI识别毒草（醉马草/狼毒）\n" + "扫描水源→评估大肠杆菌指数\n" + "连接气象数据→预测寄生虫孵化期\n" + "传统经验：观察旱獭活动区避开虫卵密集带"
    }

    override fun initListener() {
        mAdapter.setOnClickListener(object : BaseRecyclerAdapter.OnClickListener<AiConversationData> {
            override fun click(bean: AiConversationData, position: Int) {
                mMedia.stop()
                mMedia.reset()
                mMedia.setDataSource(bean.msg)
                mMedia.prepareAsync()
            }
        })

        binding.Image1.setOnDoubleClickListener {
            binding.Lin1.gone()
            binding.Lin2.visi()
            mAdapter.add(AiConversationData(AiConversationData.TYPE_RECEIVE,
                AiConversationData.MSG_TEXT,
                "    我是您的AI防疫助手，请问您遇到了什么问题？"))
        }

        binding.Rel1.setOnDoubleClickListener {
            RequestPermission.requestAudio(this@AiConversationActivity) {
                if (it) {
                    val file = File(getExternalFilesDir("")?.absolutePath, "/recode")
                    if (!file.exists()) {
                        if (!file.mkdirs()) {
                            return@requestAudio
                        }
                    }
                    val recodeFile = File(file, "${System.currentTimeMillis()}.mp3")
                    if (!recodeFile.exists()) {
                        if (!recodeFile.createNewFile()) {
                            return@requestAudio
                        }
                    }
                    mRecodePath = recodeFile.absolutePath
                    mRecode = MP3Recorder(recodeFile)
                    mRecode?.start()
                    mRecodeTime = System.currentTimeMillis()
                    mRecodeDialog.show()
                } else {
                    ToastUtils.showToast("请授予权限")
                }
            }
        }

        binding.Rel2.setOnDoubleClickListener {
            mDialog.show()
        }

        mDialog.onSend = {
            mAdapter.add(AiConversationData(AiConversationData.TYPE_SEND, AiConversationData.MSG_TEXT, it))
            binding.Recycler.smoothScrollToPosition(mAdapter.size() - 1)
            var answer = ""
            questionMap[it]?.let {
                answer = it

            } ?: let {
                answer = questionMap[questionMap.keys.random()] ?: (questionMap[questionMap.keys.first()] ?: "")
            }
            HandUtils.postTask({
                mAdapter.add(AiConversationData(AiConversationData.TYPE_RECEIVE, AiConversationData.MSG_TEXT, answer))
                binding.Recycler.smoothScrollToPosition(mAdapter.size() - 1)
            }, 500)
        }

        mRecodeDialog.onStop = {
            mRecode?.stop()
            mRecodeDialog.dismiss()

            mAdapter.add(AiConversationData(AiConversationData.TYPE_SEND,
                AiConversationData.MSG_AUDIO,
                mRecodePath,
                time = (System.currentTimeMillis() - mRecodeTime) / 1000))
            binding.Recycler.smoothScrollToPosition(mAdapter.size() - 1)
            HandUtils.postTask({
                mAdapter.add(AiConversationData(AiConversationData.TYPE_RECEIVE, AiConversationData.MSG_AUDIO, ""))
                binding.Recycler.smoothScrollToPosition(mAdapter.size() - 1)
            }, 500)
        }
    }

    override fun onDestroy() {
        mMedia.stop()
        mMedia.release()
        super.onDestroy()
    }
}